from django.core.paginator import Paginator
from django.views.generic import View
from rest_framework.response import Response

from .models import GoodsCategory,GoodsChannel,SKU
from contents.models import ContentCategory
from collections import OrderedDict
from rest_framework.generics import ListAPIView
from rest_framework.views import APIView
from .serializers import GoodsListSerializer
from rest_framework_extensions.cache.mixins import CacheResponseMixin

# Create your views here.
class CategoryView(View):
    """
    获取首页分类数据

    GET /goods/categories/
    """
    def get(self,request):
        pass

class HotGoodsListView(CacheResponseMixin,ListAPIView):
    serializer_class = GoodsListSerializer

    def get_queryset(self):
        category_id = self.kwargs.get('category_id')
        goods_set = SKU.objects.filter(category_id = category_id,is_launched=True).order_by('-sales')[:4]
        return goods_set


#####################################使用Paginator类实现分页###############################################3
class GoodsListView(APIView):
    def get(self,request,category_id):
        page = request.query_params.get('page')
        page_size = request.query_params.get('page_size')
        ordering = request.query_params.get('ordering')

        query_set = SKU.objects.filter(category_id=category_id).order_by(ordering).all()

        count = query_set.count()
        P = Paginator(query_set,page_size) #对总数据做分页处理

        curPage = P.page(page).object_list
        serializer = GoodsListSerializer(curPage,many=True)
        data = {
            'count':count,
            'results':serializer.data
        }
        return Response(data=data)

#####################################使用rest_framework自带的分页类实现分页###############################################3
# from rest_framework.pagination import PageNumberPagination

#
# class GoodsListView(ListAPIView):
#     """
#     商品列表数据
#     GET /goods/categories/(?P<category_id>\d+)/skus/?page=xxx&page_size=xxx&ordering=xxx
#     """
#     serializer_class = GoodsListSerializer
#     # 通过定义过滤后端 ，来实行排序行为
#     from rest_framework.filters import OrderingFilter
#
#     filter_backends = [OrderingFilter]
#     ordering_fields = ('create_time', 'price', 'sales')
#
#     def get_queryset(self):
#         categroy_id = self.kwargs.get("category_id")
#         return SKU.objects.filter(category_id=categroy_id, is_launched=True)


from drf_haystack.viewsets import HaystackViewSet
from .serializers import GoodsSearchSerializer
class GoodsSearchViewSet(HaystackViewSet):
    index_models = [SKU]
    serializer_class = GoodsSearchSerializer